package it.ap.sa.acqua.login.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import it.ap.sa.acqua.auth.security.CustomUserDetailsService;
import it.ap.sa.core.dao.beans.search.ResponseData;

@Controller
public class LoginCtrl {
	
	/**
	 * logger
	 */
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private CustomUserDetailsService customUserDetailsService;

	@RequestMapping(value = { "/index"}, method = RequestMethod.GET)
	public ModelAndView welcomePage() {
		
		ModelAndView  mav      		= new ModelAndView("index");
		return mav;
	}

	@RequestMapping(value = { "/homePage"}, method = RequestMethod.GET)
	public ModelAndView homePage() {
		ModelAndView model = new ModelAndView();
		model.setViewName("homePage");
		return model;
	}
	
	@RequestMapping(value = "/loginPage", method = {RequestMethod.POST,RequestMethod.GET})
	public ModelAndView loginPage(
			@RequestParam(value = "error",required = false) String error,
			@RequestParam(value = "logout",	required = false) String logout,
			@RequestParam(value = "username",required = false) String username,
			@RequestParam(value = "password",required = false) String password) {
		
		ModelAndView model = new ModelAndView();
		if (error != null) {
			model.addObject("error", "Invalid Credentials provided.");
		}

		if (logout != null) {
			model.addObject("message", "Logged out from JournalDEV successfully.");
		}

		model.setViewName("loginPage");
		return model;
	}
	
	/**
	 * Restituisce userId dell'utente in sessione 
	 */
	@RequestMapping(value = "/getUserId.pjson", method = {RequestMethod.POST,RequestMethod.GET})
	public @ResponseBody ResponseData getUserId() {
		ResponseData response = new ResponseData();
		try {
			response.setAaData(this.customUserDetailsService.getPrincipal().getUserId());			
			response.setSuccess(true);
		} catch (Exception e) {
			logger.error("Error in getUserId", e);
			response.setSuccess(false);
		}
		return response;
	}
}